import msg from "../../../utils/msg";
import { getGameDetail, getGameDetailRule, expComList, joinGame, joiner_list, joinGameRevoke, subscribe, userUpdate } from "../../../utils/request/api";
import User from "../../../utils/user";
import { parseURLParams, isFutureDate } from "../../../utils/util";
import Notify from '../../../miniprogram_npm/@vant/weapp/notify/notify';
// pages/compete/comDetail/comDetail.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    com: {} as any,
    big_pics: [],
    game_rule: '',
    showTools: false,//显示赛事管理
    tools: [
      {
        name: '报名情况',
        subname: '报名者信息列表',
        id: 1,
      },
      {
        name: '批量导入报名信息',
        subname: '通过指定Excel表格批量导入选手数据',
        id: 4,
      },
      {
        name: '导出报名情况',
        subname: 'Excel表格形式',
        id: 2,
      },
      {
        name: '抽签',
        subname: '进入抽签页面',
        id: 3,
        //openType: 'share',
      },
    ],
    is_organizer: false,//
    playerList: [{
      team_logo: "/image/微信图片_20240301024715.jpg", team_name: "张三", add_time: "2024/9/8 12:00:00", sign_game_contect: "13923705710", score: '1', team_id: 1,
      member: [
        { sign_gfid: 0, sign_name: '张三' },
      ]
    },
    ],
    signValid: true,//是否可以报名，如果不可以就显示抽签顺序
    playerNum: 0,
    has_joined:false,
    //遮盖层
    join_ready:false,//报名选手
    com_ready:false,//赛事详情
    rule_ready:false,
    is_joining:false,//防止加入时重复点击
    id:'',
  },
  _removeJavaScript(html: string): string {
    // 使用正则表达式匹配并移除<script>标签及其内容
    const regex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
    return html.replace(regex, '');
  },
  //查看赛事机构发布的所有赛事
  viewCom(){
    let club_id = this.data.com.club.club_id;
    wx.navigateTo({
      url:'/pages/user/myCom/myCom'+'?club_id='+club_id,
    });
  },
  //获取报名状态
  getJoinedState(){
    let user = new User;
    let playerList = this.data.playerList;
    playerList.forEach((item)=>{
      if(item.member[0].sign_gfid==user.GF_ID){
        this.setData({
          has_joined:true,
        });
      }
    });
  },
  showPhone() {
    this.setData({
      showPhone: true
    });
  },
  openMap() {
    msg.show('该赛事不支持定位', '');
  },
  onSelectPhone(event: any) {
    wx.makePhoneCall({
      phoneNumber: event.detail.name,
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  //判断是否可以报名
  judgeSignValid() {
    let sign_end = this.data.com.game_data[0].signup_date_end;
    //console.log('sign_end=',sign_end);
    this.setData({
      signValid: isFutureDate(sign_end),
    });
  },
  viewMore() {
    let com = this.data.com;
    com = JSON.stringify({
      title: com.game_title,
      count: com.subscribes,
      game_id: com.id,
      game_data_id: com.game_data[0].id,
      max_num: com.game_data[0].max_num_team,
      game_club_id:com.game_club_id,
    });
    wx.navigateTo({
      url: "../player/player?com=" + com,
    });
  },

  async onSelect(e: any) {
    let id = e.detail.id;
    let com = this.data.com;
    com = JSON.stringify({
      title: com.game_title,
      count: com.subscribes,
      game_id: com.id,
      game_data_id: com.game_data[0].id,
      max_num: com.game_data[0].max_num_team,
      game_club_id:com.game_club_id,
    });
    switch (id) {
      case 1:
        wx.navigateTo({
          url: "../player/player?com=" + com,
        });
        break;
      case 4:
        //导入
        this.importPlayer(com);
        break;
      case 2:
        msg.Loading('导出报名情况中');
        await expComList(JSON.stringify(this.data.playerList), com, '选手名单');
        msg.hideLoading();
        break;
      case 3:
        wx.navigateTo({
          url: "../player/player?com=" + com + "&showDraw=" + true,
        });
        break;
    }
  },
  //通过excel导入选手信息
  importPlayer(com:any) {
    wx.navigateTo({
      url: "../import/import?com="+com,
    });

  },
  onClose() {
    this.setData({
      showTools: false,
      showPhone: false,
    });
  },
  showTools() {
    this.setData({
      showTools: true,
    });
  },
  //报名
  async join() {
    //todo
    let user = new User();
    if (!user.checkLogin(1)) return;
    this.setData({is_joining:true});
    //let res: any = await joinGame({ GF_ID: user.GF_ID, game_id: this.data.com.id, game_data_id: this.data.com.game_data[0].id, team_logo: user.head_pic,team_name:user.name });
    //msg.hideLoading();
    if (!this.data.has_joined) {//报名
      if (this.data.com.game_data[0].max_num_team <= (this.data.playerList.length + this.data.playerNum)) {
        msg.show('报名人数已满'); return;
      }
      wx.navigateTo({
        url:"/pages/pay/pay"+"?id="+this.data.com.id+'&type=1',
      });
      // msg.Loading();
      // let res: any = await joinGame({ GF_ID: user.GF_ID, game_id: this.data.com.id, game_data_id: this.data.com.game_data[0].id, team_logo: user.head_pic,team_name:user.name });
      // msg.hideLoading();
      // if (res.data.error == 0) this.setData({ has_joined: true });
      // msg.show('报名成功');
    }
    else {
      //退出报名
      await msg.confirm('您已申请报名该赛事', '若要退出报名，请点击确认');
      await msg.confirm('为防止误触，请再次确认是否退出该赛事的报名', '赛事名称:' + this.data.com.game_title);
      //退出报名
      msg.Loading();
      let res: any = await joinGameRevoke({ GF_ID: user.GF_ID, game_data_id: this.data.com.game_data[0].id });
      msg.hideLoading();
      if (res.data.error == 0){ 
        this.setData({ has_joined: false });
        this.onShow();
        Notify({ type: "danger", message: '退出报名成功'  });
      }
      else msg.show(res.data.msg, '');
    }
    
    this.setData({is_joining:false});
  },
  goToMain() {
    wx.switchTab({
      url: "/pages/compete/compete",
    })
  },
  share() {
    //todo
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success:(res)=>{
        console.log('res=',res);
      },
      fail(err){
        console.log('err=',err);
      }
    });
  },
  //关注-取关
  follow: async function () {
    let club = this.data.com.club;
    if (club.is_subscribe){ 
      await msg.confirm('是否确认取关', '');
    }
    //todo 储存关注
    let user = new User;
    let res:any = await subscribe({GF_ID:user.GF_ID,type:1,control:(club.is_subscribe?0:1),id:club.club_id});
    if(res.data.error==0) Notify({ type: (club.is_subscribe?'warning':'success'), message: res.data.msg });
    else Notify({ type: "danger", message: res.data.msg  });

    this.setData({
      ['com.club.is_subscribe']: (club.is_subscribe?0:1),
    });
  },
    //收藏-取关
    store: async function () {
      let com = this.data.com;
      let is_subscribe=(this.data.com.is_subscribe==1);
      if (is_subscribe){ 
        await msg.confirm('是否取消收藏', '');
      }
      //todo 储存关注
      let user = new User;
      let res:any =await subscribe({GF_ID:user.GF_ID,type:2,control:(is_subscribe?0:1),id:com.id})
      if(res.data.error==0) Notify({ type: (is_subscribe?'warning':'success'), message: (is_subscribe?'取消收藏':'收藏成功') });
      else Notify({ type: "danger", message: res.data.msg  });
      
      this.setData({
        ['com.is_subscribe']: (is_subscribe?0:1),
        ['com.subscribes']:(is_subscribe ? this.data.com.subscribes-1 : this.data.com.subscribes+1),
      });
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options: any) {
    let id = options.id;
    this.setData({
      id:id,
    });
  },
  showImgDetail(e: any) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url],
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:async function() {
    let id = this.data.id;
    let user = new User;
    this.setData({
      join_ready:false,
      com_ready:false,
      rule_ready:false,
    });
    msg.Loading();
    let res: any = await getGameDetail({GF_ID:user.GF_ID,game_id:id,AccessKeyId:user.AccessKey.AccessKeyId,AccessKeySecret:user.AccessKey.AccessKeySecret}).then(async (res: any) => { return res; });
    if (res.data.error != 0) {
      msg.hideLoading();
      await msg.show(res.data.msg); 
      if(res.data.error==2) wx.navigateBack();
      return;
    }
    let com = res.data.datas;
    if (com.signup_date) com.signup_date = com.signup_date.replaceAll('-', '/');
    if (com.game_time) com.game_time = com.game_time.replaceAll('-', '/');
    if (com.game_time_end) com.game_time_end = com.game_time_end.replaceAll('-', '/');
    if(com.game_data)
    if (com.game_data[0].signup_date_end) com.game_data[0].signup_date_end = com.game_data[0].signup_date_end.replaceAll('-', '/');
    this.setData({
      com: com,
      com_ready:true,
      is_organizer: (com.game_club_id == user.club_id),
    });
    this.judgeSignValid();
    //轮播图
    if (com.game_big_pic)
      this.setData({
        big_pics: com.game_big_pic.split(','),
      });
    //赛事详情
    if(com.game_rule[0])
    if (com.game_rule[0].url) {
      let rule_url = com.game_rule[0].url;
      let params = parseURLParams(rule_url);
      if (params.id) {
        let res_rule: any = await getGameDetailRule(params.id).then((res) => { return res; });
        this.setData({
          game_rule: this._removeJavaScript(res_rule.data),
          rule_ready:true,
        });
      }
    }
    //报名列表
    await joiner_list({ game_id: this.data.com.id, game_data_id: this.data.com.game_data[0].id })
      .then((res: any) => {
        let playerList: any[] = res.data.datas;
        let playerNum = 0;
        if (playerList.length > 6) {
          playerList.splice(4, playerList.length - 5);
          playerNum = playerList.length;
        }
        this.setData({
          playerList: playerList,
          playerNum,
          join_ready:true,
        });
        this.getJoinedState();//获取报名状态
      });
    msg.hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})